//
//  SettingViewController.m
//  SecretFolder
//
//  Created by Deepak Kumar on 25/06/12.
//  Copyright 2012 Frog. All rights reserved.
//

#import "SettingViewController.h"
#import "ChangePasswordViewController.h"
#import "PasswordViewController.h"
#import "PasswordchoiceViewController.h"
//#import "AppearanceChoiceViewController.h"
@implementation SettingViewController
@synthesize mTableView;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
//    if ([[NSUserDefaults standardUserDefaults] objectForKey:kDecoyPassword]) {
//        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kDecoyPasswordOn];
//    }
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	self.navigationItem.title = @"Settings";
    NSMutableDictionary *size = [NSMutableDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Helvetica" size:19],UITextAttributeFont,nil];
    [size setObject:[UIColor blackColor] forKey:UITextAttributeTextColor];
    self.navigationController.navigationBar.titleTextAttributes = size;
	self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    //self.navigationController.navigationBar.translucent = YES;
    
    self.navigationItem.rightBarButtonItem =
	[[UIBarButtonItem alloc] initWithTitle:@"Done"
									  style:UIBarButtonSystemItemAction
									 target:self
									 action:@selector(cancelButton:)];
    self.navigationItem.rightBarButtonItem.style = UIBarButtonItemStylePlain;
   //    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleDone target:self action:@selector(goback:)];
}
-(void)viewDidAppear:(BOOL)animated
{
    [mTableView reloadData];
}

 - (IBAction) cancelButton:(id)sender
{
	[self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

 - (IBAction) saveButton:(id)sender
{
	[self cancelButton:sender];
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 3;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
   if (section == 0) {
       if([[NSUserDefaults standardUserDefaults] boolForKey:kDecoyPasswordOn] && [[NSUserDefaults standardUserDefaults] boolForKey:kPasswordSaved]&& [[NSUserDefaults standardUserDefaults] boolForKey:kDecoyPasswordEntered] == NO )
       {
           return 5;
       }
       else if ([[NSUserDefaults standardUserDefaults] boolForKey:kDecoyPasswordEntered] == YES) {
           return 3;
       }
	   if ([[NSUserDefaults standardUserDefaults] boolForKey:kPasswordSaved]) {
		   return 4;
	   }
       
	   else {
		   return 1;
	   }
   }
	else if (section == 1) {
		return 2;
	}
    else if (section == 2) {
		return 1;
	}
	return 0;
}

-(void)goback:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    // Configure the cell...
    if (indexPath.section == 0) {
		if (indexPath.row == 0) {
			cell.textLabel.text = @"Password";
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
			UISwitch *pSwitchView = [[UISwitch alloc] initWithFrame:CGRectZero];
			cell.accessoryView = pSwitchView;
			
			if ([[NSUserDefaults standardUserDefaults] boolForKey:kPasswordSaved]) {
				[pSwitchView setOn:YES animated:NO];
			}
			else {
				[pSwitchView setOn:NO animated:NO];
			}
			
			[pSwitchView addTarget:self action:@selector(passwordSwitchChanged:) forControlEvents:UIControlEventValueChanged];
			
		}
		else if (indexPath.row == 1) {
			cell.textLabel.text = @"Set Password";
			cell.accessoryView = nil;
			cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

		}
		else if (indexPath.row == 2) {
			cell.textLabel.text = @"Change Password";
			cell.accessoryView = nil;
			cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		}
        else if (indexPath.row == 3){
            cell.textLabel.text = @"Decoy Password";
            
			UISwitch *pSwitchView = [[UISwitch alloc] initWithFrame:CGRectZero];
			cell.accessoryView = pSwitchView;
			
			if ([[NSUserDefaults standardUserDefaults] boolForKey:kDecoyPasswordOn]) {
				[pSwitchView setOn:YES animated:NO];
			}
			else {
				[pSwitchView setOn:NO animated:NO];
			}
			
			[pSwitchView addTarget:self action:@selector(decoyPasswordSwitchChanged:) forControlEvents:UIControlEventValueChanged];
        }
        else if (indexPath.row == 4)
        {
            if ([[NSUserDefaults standardUserDefaults] objectForKey:kDecoyPassword]) {
                cell.textLabel.text = @"Change Decoy Passoword";
                 cell.accessoryView = nil;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
            else
            {
                cell.textLabel.text = @"Set Decoy Passoword";
                cell.accessoryView = nil;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
        }
	}
	else if (indexPath.section == 1) {
		if (indexPath.row == 0) {
			cell.textLabel.text = @"Share via wifi";
			cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

		}
		else if (indexPath.row == 1) {
			cell.textLabel.text = @"Share directory";
			
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
			UISwitch *dSwitchView = [[UISwitch alloc] initWithFrame:CGRectZero];
			cell.accessoryView = dSwitchView;
			
			if ([[NSUserDefaults standardUserDefaults] boolForKey:kShareDirectory]) {
				[dSwitchView setOn:YES animated:NO];
			}
			else {
				[dSwitchView setOn:NO animated:NO];
			}

			[dSwitchView addTarget:self action:@selector(shareSwitchChanged:) forControlEvents:UIControlEventValueChanged];
		}
	}
    else if (indexPath.section == 2 )
    {
        cell.textLabel.text=@"Appearance";
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
        
    }
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:15];
    return cell;
}

- (void) passwordSwitchChanged:(UISwitch *)pSwitch {
    NSLog( @"passwordSwitchChanged is %@", pSwitch.on ? @"ON" : @"OFF" );
	
	[[NSUserDefaults standardUserDefaults] setBool:pSwitch.on forKey:kPasswordSaved];
	//[self.mTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationBottom];
	[self.mTableView reloadSections:[NSIndexSet indexSetWithIndex:0]
				  withRowAnimation:UITableViewRowAnimationNone];
}
- (void) decoyPasswordSwitchChanged:(UISwitch *)pSwitch {
    NSLog( @"passwordSwitchChanged is %@", pSwitch.on ? @"ON" : @"OFF" );
	if (pSwitch.on == NO) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kDecoyPassword];
        [mTableView reloadData];
    }
	[[NSUserDefaults standardUserDefaults] setBool:pSwitch.on forKey:kDecoyPasswordOn];
    [[NSUserDefaults standardUserDefaults] synchronize];
    //[[NSUserDefaults standardUserDefaults] setBool:pSwitch.on forKey:kSetDecoyPassword];

	//[self.mTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationBottom];
	[self.mTableView reloadSections:[NSIndexSet indexSetWithIndex:0]
                   withRowAnimation:UITableViewRowAnimationNone];
}
- (void) shareSwitchChanged:(UISwitch *)pSwitch {
	
    NSLog( @"shareSwitchChanged is %@", pSwitch.on ? @"ON" : @"OFF" );
	[[NSUserDefaults standardUserDefaults] setBool:pSwitch.on forKey:kShareDirectory];

}




#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
   	[tableView deselectRowAtIndexPath:indexPath animated:YES];

	if (indexPath.section == 0) {
		if (indexPath.row == 1) {
//			PasswordViewController *tController = [[PasswordViewController alloc] initWithNibName:@"PasswordViewController" bundle:nil];
//			[self.navigationController pushViewController:tController  animated:YES];
            PasswordchoiceViewController *tController=[[PasswordchoiceViewController alloc] initWithNibName:@"PasswordchoiceViewController" bundle:Nil];
            [self.navigationController pushViewController:tController  animated:YES];
		}
		else if (indexPath.row == 2) {
            if ([[NSUserDefaults standardUserDefaults] objectForKey:kPasswordText]==Nil&&[[NSUserDefaults standardUserDefaults] objectForKey:kPattern]==Nil) {
                UIAlertView *tNoPasswordAlert=[[UIAlertView alloc] initWithTitle:@"No Password" message:@"Please set a password before changing" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
                [tNoPasswordAlert show];
            }
            else if([[NSUserDefaults standardUserDefaults] objectForKey:kPattern]==Nil)
            {
			ChangePasswordViewController *tController = [[ChangePasswordViewController alloc] initWithNibName:@"ChangePasswordViewController" bundle:nil];
			[self.navigationController pushViewController:tController  animated:YES];
            }
            else if([[NSUserDefaults standardUserDefaults] objectForKey:kPasswordText]==Nil)
            {
             DrawPatternLockViewController *tController=           [[DrawPatternLockViewController alloc] init];
                tController.delegate = self;
                [tController setTarget:self withAction:@selector(checkKey:)];
              //  self.navigationController.delegate = self;
                [self.navigationController pushViewController:tController  animated:YES];
                //[tController release];
            }
		}
        else if (indexPath.row == 4){
            if (![[NSUserDefaults standardUserDefaults] objectForKey:kPattern]) {
                UIAlertView *tAlertView=[[UIAlertView alloc] initWithTitle:@"Set Password" message:@"You Should set Actual password first" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [tAlertView show];
            }
            else
            {
            [self pushDecoyPatternPasswordController];
            }
        }
	}
    else if( indexPath.section == 2){
    //    AppearanceChoiceViewController *tController=[[AppearanceChoiceViewController alloc] initWithNibName:@"AppearanceChoiceViewController" bundle:nil];
    //    [self.navigationController pushViewController:tController animated:YES];
    }
}
-(void)checkKey:(NSString *)pkey1
{
    
    NSLog(@"------pattern %@ key1 %@ pattern1 %@",[[NSUserDefaults standardUserDefaults] objectForKey:kPattern],pkey1,[[NSUserDefaults standardUserDefaults] objectForKey:kPattern1]);
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:kPattern ] isEqual:pkey1]) {
                
       [self performSelector:@selector(pushPatternPasswordController) withObject:nil afterDelay:0.1];
    }else
    {
        UIAlertView *tAlertView=[[UIAlertView alloc] initWithTitle:@"Incorrect Pattern" message:@"You Have Entered wrong Password" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Retry", nil];
        [tAlertView show];
    }

}
-(BOOL)checkDecoyKey:(NSString *)pkey
{
    NSLog(@"-----decoy password %@",[[NSUserDefaults standardUserDefaults] objectForKey:kDecoyPassword]);
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:kDecoyPassword]isEqual:pkey]) {
//        if ([[NSUserDefaults standardUserDefaults] objectForKey:kPattern1]) {
//            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kPattern1];
//            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kPattern2];
//        }
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kChangeDecoyPassword];
        DrawPatternLockViewController *tController =[DrawPatternLockViewController new];
        [tController setTarget:self withAction:@selector(compareDecoyKey:key2:)];
        [self.navigationController pushViewController:tController animated:YES];
        return YES;
    }
    else
    {
        UIAlertView *tAlertView=[[UIAlertView alloc] initWithTitle:@"Incorrect Pattern" message:@"You Have Entered wrong Password" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Retry", nil];
        [tAlertView show];
    }
    return NO;
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([[alertView buttonTitleAtIndex:buttonIndex] isEqual:@"Cancel"]) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    if (alertView.tag == 1) {
        
    }
}

-(void)pushDecoyPatternPasswordController
{
    DrawPatternLockViewController *tController = [DrawPatternLockViewController new];
    
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:kDecoyPassword]) {
        [tController setTarget:self withAction:@selector(checkDecoyKey:)];
    }
    else
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kSetDecoyPassword];
        [tController setTarget:self withAction:@selector(compareDecoyKey:key2:)];
    }
    [self.navigationController pushViewController:tController animated:YES];
}
-(void)pushPatternPasswordController
{
    DrawPatternLockViewController *tController= [DrawPatternLockViewController new];
    [[NSUserDefaults standardUserDefaults] setObject:@"New Password" forKey:@"NewPassword"];
    [tController setTarget:self withAction:@selector(compareKey:key2:)];
    
    [self.navigationController pushViewController:tController animated:YES];
}
-(void)compareKey:(NSString *)pkey1 key2:(NSString *)pkey2
{
    if ([pkey1 isEqual:pkey2]) {
        if ([pkey1 isEqual:[[NSUserDefaults standardUserDefaults]objectForKey:kDecoyPassword]]) {
        }
        else
        {
        [[NSUserDefaults standardUserDefaults] setObject:pkey1 forKey:kPattern];
        [[NSUserDefaults standardUserDefaults] synchronize];
        UIAlertView *talert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Your password has been changed successfully." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
		[talert show];
        [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
}

-(void)compareDecoyKey:(NSString *)pkey1 key2:(NSString *)pkey2
{
    if ([pkey1 isEqual:pkey2]) {
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:kPattern] isEqual:pkey1]) {
//            UIAlertView *talert = [[UIAlertView alloc] initWithTitle:@"Duplicate" message:@"Your Decoy password cannot be equal to Actual Password." delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"Retry", nil];
//            talert.tag = 1;
////            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kSetDecoyPassword];
//            [talert show];
        }
        else
        {
            if ([[NSUserDefaults standardUserDefaults] objectForKey:kDecoyPassword]) {
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:kDecoyPassword];
            }
        [[NSUserDefaults standardUserDefaults] setObject:pkey1 forKey:kDecoyPassword];
        [[NSUserDefaults standardUserDefaults] synchronize];
        UIAlertView *talert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Your Decoy password has been set successfully." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
		[talert show];
        [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Override to allow orientations other than the default portrait orientation.
    return UIInterfaceOrientationIsLandscape(interfaceOrientation)? YES : NO;
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
	self.mTableView = nil;
}




@end

